from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.status import HTTP_400_BAD_REQUEST
from apps.questions.models import Label, Question, Reply
from apps.questions.serializers import QuestionsModelSerializer, ReplyModelSerializer, LabelModelSerializer
from django_redis import get_redis_connection

class LabelsAPIView(APIView):
    # /labels/  GET
    def get(self, request):
        data = []
        labels = Label.objects.all()
        for label in labels:
            data.append({
                'id': label.id,
                'labe_name': label.label_name
            })
        return Response(data)


class LabelsFullAPIView(APIView):
    def get(self, request):
        labels = Label.objects.all()
        data = []

        for label in labels:
            data.append({
                'id': label.id,
                'label_name': label.label_name,
                'users': [user.id for user in label.users.all()],
            })
        return Response(data)


class UsersLabelsAPIView(APIView):
    # /labels/users/ GET
    def get(self, request):
        user = request.user
        labels = user.labels.all()
        data = []
        for label in labels:
            data.append({
                'id': label.id,
                'labe_name': label.label_name
            })
        return Response(data)


# ********************************************
class NewQuestionsLabel(APIView):
    # /questions/{id}/label/new/  GET
    def get(self, request, id):
        if id != "-1":
            try:
                label = Label.objects.get(id=id)
            except Label.DoesNotExist:
                return Response(HTTP_400_BAD_REQUEST)
            questions = label.questions.filter(solve__isnull=False).order_by('-createtime')
        else:
            questions = Question.objects.filter(solve__isnull=False).order_by('-createtime')
        serializer = QuestionsModelSerializer(questions, many=True)
        return Response(serializer.data)


class HotQuestionsLabel(APIView):
    # /questions/{id}/label/hot/  GET
    def get(self, request, id):
        if id != "-1":
            try:
                label = Label.objects.get(id=id)
            except Label.DoesNotExist:
                return Response(HTTP_400_BAD_REQUEST)
            questions = label.questions.filter(solve__isnull=False).order_by('-reply')
        else:
            questions = Question.objects.filter(solve__isnull=False).order_by('-reply')
        serializer = QuestionsModelSerializer(questions, many=True)
        return Response(serializer.data)


class WaitQuestionsLabel(APIView):
    # /questions/{id}/label/wait/ GET
    def get(self, request, id):
        if id != "-1":
            try:
                label = Label.objects.get(id=id)
            except Label.DoesNotExist:
                return Response(HTTP_400_BAD_REQUEST)
            questions = label.questions.filter(solve__isnull=True).order_by('-createtime')
        else:
            questions = Question.objects.filter(solve__isnull=True).order_by('-createtime')
        serializer = QuestionsModelSerializer(questions, many=True)
        return Response(serializer.data)


# *************************************************
class QuestionsAPIView(APIView):
    # /questions/ POST
    def post(self, reqeust):
        data = reqeust.data
        title = data.get('title')
        content = data.get('content')
        labels = data.get('labels')
        user = reqeust.user
        question = Question.objects.create(title=title, content=content, user=user)
        question.labels.add(*labels)
        return Response({
            'message': question.title,
            'success': True
        })


class QuestionsQueryAPIView(APIView):
    # /questions/{id}/ GET
    def get(self, request, id):
        try:
            question = Question.objects.get(id=id)
        except Question.DoesNotExist:
            return Response(HTTP_400_BAD_REQUEST)
        question.visits += 1
        question.save()
        serializer = QuestionsModelSerializer(question)
        data = dict(serializer.data)
        # comment_question 问题的评论列表
        comments = question.replies.filter(type=0)
        comment_question = ReplyModelSerializer(comments, many=True)
        data['comment_question'] = comment_question.data
        # "subs" 回复的回复，自关联
        # answer_question 问题的回答列表
        answers = question.replies.filter(type=2)
        answer_question = ReplyModelSerializer(answers, many=True)
        data['answer_question'] = answer_question.data

        return Response(data)


class QuestionsUseful(APIView):
    def put(self, request, id):
        try:
            question = Question.objects.get(id=id)
        except Question.DoesNotExist:
            return Response(HTTP_400_BAD_REQUEST)
        redis_conn = get_redis_connection('useful')
        pl= redis_conn.pipeline()
        # 判断redis中用户是否评价过
        result = redis_conn.hget('question_%s' % request.user.id,'markquestion_%s' % question.id )
        if result:
            result=result.decode()
        if result == 'useful':
            return Response({
            "message": '已评价过',
            "success": False
        })
        elif result == 'unuseful':
            question.useful_count += 1
            question.unuseful_count -= 1
            pl.hset('question_%s' % request.user.id,'markquestion_%s' % question.id,'useful')
        else:
            question.useful_count += 1
            pl.hset('question_%s' % request.user.id,'markquestion_%s' %  question.id, 'useful')
        pl.execute()
        redis_conn.close()
        question.save()
        return Response({
            "message": '操纵成功',
            "success": True
        })


class QuestionsUnuseful(APIView):
    def put(self, request, id):
        try:
            question = Question.objects.get(id=id)
        except Question.DoesNotExist:
            return Response(HTTP_400_BAD_REQUEST)
        redis_conn = get_redis_connection('useful')
        pl = redis_conn.pipeline()
        # 判断redis中用户是否评价过
        result = redis_conn.hget('question_%s' % request.user.id,'markquestion_%s' % question.id)
        if result:
            result=result.decode()
        if result == 'unuseful':
            return Response({
                "message": '已评价过',
                "success": False
            })
        elif result == 'useful':
            question.useful_count -= 1
            question.unuseful_count += 1
            pl.hset('question_%s' % request.user.id, 'markquestion_%s' % question.id, 'unuseful')
        else:
            question.unuseful_count += 1
            pl.hset('question_%s' % request.user.id,'markquestion_%s' % question.id, 'unuseful')
        pl.execute()
        redis_conn.close()
        question.save()
        return Response({
            "message": '操纵成功',
            "success": True
        })


# ********************回答问题***************************
class ReplyAPIView(APIView):
    # /reply/ post
    def post(self, reqeust):
        user = reqeust.user
        data = reqeust.data
        problem = data.get('problem')
        content = data.get('content')
        type = data.get('type')
        parent = data.get('parent')

        if type == 2:
            question = Question.objects.get(id=problem)
            question.solve = 1
            question.reply += 1
            question.save()
        reply = Reply.objects.create(user=user, problem_id=problem, type=type, content=content, parent_id=parent)

        return Response({
            'message': '评论成功',
            'success': True
        })


class ReplyUseful(APIView):
    def put(self, request, id):
        try:
            reply = Reply.objects.get(id=id)
        except Question.DoesNotExist:
            return Response(HTTP_400_BAD_REQUEST)
        redis_conn = get_redis_connection('useful')
        pl = redis_conn.pipeline()
        # 判断redis中用户是否评价过
        result = redis_conn.hget('reply_%s' % request.user.id, 'markreply_%s'%reply.id)
        if result:
            result=result.decode()
        if result == 'useful':
            return Response({
                "message": '已评价过',
                "success": False
            })
        elif result == 'unuseful':
            reply.useful_count += 1
            reply.unuseful_count -= 1
            pl.hset('reply_%s' % request.user.id, 'markreply_%s' % reply.id, 'useful')
        else:
            reply.useful_count += 1
            pl.hset('reply_%s' % request.user.id, 'markreply_%s' % reply.id, 'useful')
        pl.execute()
        redis_conn.close()
        reply.save()
        return Response({
            "message": '操纵成功',
            "success": True
        })


class ReplyUnuseful(APIView):
    def put(self, request, id):
        try:
            reply = Reply.objects.get(id=id)
        except Question.DoesNotExist:
            return Response(HTTP_400_BAD_REQUEST)
        redis_conn = get_redis_connection('useful')
        pl = redis_conn.pipeline()
        # 判断redis中用户是否评价过
        result = redis_conn.hget('reply_%s' % request.user.id, 'markreply_%s'%reply.id)
        if result:
            result=result.decode()
        if result == 'unuseful':
            return Response({
                "message": '已评价过',
                "success": False
            })
        elif result == 'useful':
            reply.useful_count -= 1
            reply.unuseful_count += 1
            pl.hset('reply_%s' % request.user.id,'markreply_%s'%reply.id, 'unuseful')
        else:
            reply.unuseful_count += 1
            pl.hset('reply_%s' % request.user.id,'markreply_%s'%reply.id, 'unuseful')
        pl.execute()
        redis_conn.close()
        reply.save()
        return Response({
            "message": '操纵成功',
            "success": True
        })


# *******************************************************

# **********************关注标签*************************
class LabelUnfocusin(APIView):
    # /labels/{id}/focusin/ PUT
    def put(self, request, id):
        try:
            label = Label.objects.get(id=id)
        except Question.DoesNotExist:
            return Response(HTTP_400_BAD_REQUEST)
        user = request.user
        label.users.remove(user)
        label.save()
        return Response({
            "message": '已取消关注',
            "success": True
        })


class LabelFocusin(APIView):
    # /labels/{id}/focusin/ PUT
    def put(self, request, id):
        try:
            label = Label.objects.get(id=id)
        except Question.DoesNotExist:
            return Response(HTTP_400_BAD_REQUEST)
        user = request.user
        label.users.add(user)
        label.save()
        return Response({
            "message": '已关注',
            "success": True
        })


# class LabelQueryAPIView(APIView):
#     def get(self,request,id):
#         try:
#             label = Label.objects.get(id=id)
#         except Label.DoesNotExist:
#             return Response(HTTP_400_BAD_REQUEST)
#         serializer = LabelModelSerializer(label)
#
#         return Response(serializer.data)


class LabelQueryAPIView(APIView):
    def get(self, request, id):
        try:
            label = Label.objects.get(id=id)
        except Label.DoesNotExist:
            return Response(HTTP_400_BAD_REQUEST)
        serializer = LabelModelSerializer(label)
        data = serializer.data
        questions = label.questions.all()
        questions_data = QuestionsModelSerializer(questions, many=True).data
        data['questions'] = questions_data
        return Response(data)
